/**
 * import api from './api/index.js'
 * Vue.prototype.$http = api
 * ----------------------
 * 组件中使用方法(以post为例):
 * 示例：this.$http.post(url, data, option).then((res)=>{})
 * 使用注意：
 *  - 传参格式：
 *    - url: '/user/userLogin'
 *    - data: object | null
 *    - option: {type: json|formData|multipart, headers: {}}
 *  - url地址对象建议使用单独的js文件管理
 */

import Vue from 'vue'
import store from '@/store'
// 引用axios
import axios from 'axios'
import { Message } from 'element-ui'
// import { IEVersion } from '@/assets/js/utils.js'
// import nuc from '../assets/js/nuc'
import cookie from '../assets/js/cookie'
const whiteUrl = [ '/getLoginUserInfo', '/authority/queryMenuList', 'personalTask/queryPersonalTask', 'personalTask/queryPersonalAlert' ]  // 请求白名单，不需要携带 Token 的请求
// import { reject, resolve } from 'core-js/fn/promise'
// axios.defaults.withCredentials = true
const BASE_URL = '/pmis/'
axios.defaults.timeout = 30000

// 请求拦截
axios.interceptors.request.use((config) => {
  const url = config.url.replace(config.baseURL, '')
  // 判断请求的url是否在白名单中，存在就直接 return config
  
  if (whiteUrl.some(wl => url === wl)) {
    Vue.prototype.$loading.showLoading()
    return config
  } else {
    const key = Vue.prototype.$cookieStore.getCookie('empCompanyCode')
    // const token = Vue.prototype.$cookieStore.getCookie('Authorization')
    if (key) {
      config.headers['psId'] = cookie.setPsId()
      config.headers['empCompanyCode'] = cookie.setEmpCompanyCode()
      Vue.prototype.$loading.showLoading()
      return config
    } else {
      Message.error('登录已过期')
      setTimeout(() => {
        sessionStorage.clear()
        store.commit('clearState')
        Vue.prototype.$cookieStore.delCookie('Authorization')
        Vue.prototype.$cookieStore.delCookie('empCompanyCode')
        window.location.href = `${window.location.origin}/LoginApp/v1/logout?redirectUrl=${window.location.origin}/pmis-pc/`
      }, 1000)
      return config
    }
  }
})

// 回调拦截
axios.interceptors.response.use((res) => {
  if (res.status === 200) {
    Vue.prototype.$loading.hideLoading()
  }
  return res
}, (err) => {
  if (err && err.response) {
    Vue.prototype.$loading.hideLoading()
    switch (err.response.status) {
      case 400:
        err.message = '错误请求'
        break
      case 401:
        err.message = '未授权，请重新登录'
        break
      case 403:
        err.message = '没有权限，拒绝访问'
        break
      case 404:
        err.message = '请求错误,未找到该资源'
        break
      case 405:
        err.message = '请求方法未允许'
        break
      case 408:
        err.message = '请求超时'
        break
      case 500:
        err.message = '服务器端出错'
        break
      case 501:
        err.message = '网络未实现'
        break
      case 502:
        err.message = '网络错误'
        break
      case 503:
        err.message = '服务不可用'
        break
      case 504:
        err.message = '网络超时'
        break
      case 505:
        err.message = 'http版本不支持该请求'
        break
      default:
        err.message = `连接错误${err.response.status}`
    }
  }
  // 错误处理
  if (err.message) {
    console.log(err.message)
    Vue.prototype.$message.error('登陆出错')
    if (err.response.status === 401) {
      return false
    }
  }
  return Promise.reject(err)
})
const apiAxios = (option = {}) => {
  const {
    method = 'get',
    baseURL = BASE_URL,
    dataType = 'json',
  } = option
  // 封装headers
  const CONTENT_TYPE = {
    json: 'application/json; charset=UTF-8',
    formData: 'application/x-www-form-urlencoded; charset=UTF-8',
    multipart: 'multipart/form-data; charset=UTF-8'
  }
  const headers = {
    // Authorization: process.env.VUE_APP_LOCAL_AUTH,
    'Content-Type': CONTENT_TYPE[option.dataType]
  }
  // const localAuth = process.env.VUE_APP_LOCAL_AUTH
  // if (localAuth) {
  //   headers.Authorization = localAuth
  // }
  // const ieVer = IEVersion()
  // if (ieVer !== -1 && ieVer !== 'edge') {
  //   headers['Cache-Control'] = 'no-cache'
  //   headers['Pragma'] = 'no-cache'
  // }
  if (option.headers) Object.assign(headers, option.headers)
  const realOption = {
    ...option,
    method,
    baseURL,
    headers,
    dataType,
    withCredentials: true
  }
  return new Promise((resolve, reject) => {
    axios(realOption).then((res) => {
      if (res.status === 200 && res.data.code === 0) {
        resolve({
          success: true,
          data: res.data.body,
          response: res
        })
      } else {
        resolve({
          success: false,
          data: res.data,
          response: res
        })
      }
    }).catch((err) => {
      reject({
        success: false,
        data: err.message,
        response: err
      })
    })
  })
}

// 返回在vue模板中的调用接口
export default {
  get(url, params, option) {
    return apiAxios({
      method: 'GET',
      url,
      params,
      ...option
    })
  },
  post(url, data, option) {
    return apiAxios({
      method: 'POST',
      url,
      data,
      ...option
    })
  },
  put(url, data, option) {
    return apiAxios({
      method: 'PUT',
      url,
      data,
      ...option
    })
  },
  delete(url, data, option) {
    return apiAxios({
      method: 'DELETE',
      url,
      data,
      ...option
    })
  }
}
